package com.jin.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jin.common.exception.NoStockException;
import com.jin.common.to.OrderTo;
import com.jin.common.to.es.SeckillOrderTo;
import com.jin.common.utils.R;
import com.jin.common.vo.MemberRespVo;
import com.jin.gulimall.order.constant.OrderTokenConstant;
import com.jin.gulimall.order.entity.OrderItemEntity;
import com.jin.gulimall.order.entity.PaymentInfoEntity;
import com.jin.gulimall.order.enume.OrderStatusEnum;
import com.jin.gulimall.order.feign.CartFeignService;
import com.jin.gulimall.order.feign.MemberFeignService;
import com.jin.gulimall.order.feign.ProductFeignService;
import com.jin.gulimall.order.feign.WmsFeignService;
import com.jin.gulimall.order.interceptor.LoginUserInterceptor;
import com.jin.gulimall.order.service.OrderItemService;
import com.jin.gulimall.order.service.PaymentInfoService;
import com.jin.gulimall.order.to.OrderCreateTo;
import com.jin.gulimall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jin.common.utils.PageUtils;
import com.jin.common.utils.Query;

import com.jin.gulimall.order.dao.OrderDao;
import com.jin.gulimall.order.entity.OrderEntity;
import com.jin.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    public ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();
    @Resource
    MemberFeignService memberFeignService;

    @Resource
    CartFeignService cartFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );
        return new PageUtils(page);
    }

    /**
     * 订单确认页需要的数据
     *
     * @return
     */
    @Override
    public OrderConfirmVo orderConfirm() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        System.out.println("主线程..." + Thread.currentThread().getId());
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //1.远程查询所有收货地址列表
            //每个请求都共享之前的数据
            RequestContextHolder.setRequestAttributes(attributes);
            System.out.println("address线程..." + Thread.currentThread().getId());
            List<MemberAddressVo> address = memberFeignService.getAdress(memberRespVo.getId());
            orderConfirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //2.远程查询购物车中所有选中的购物项
            //每个请求都共享之前的数据
            RequestContextHolder.setRequestAttributes(attributes);
            System.out.println("cart线程..." + Thread.currentThread().getId());
            List<OrderItemVo> items = cartFeignService.getCurrentCartItems();
            orderConfirmVo.setItems(items);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R skusHasStock = wmsFeignService.getSkusHasStock(collect);
            List<SkuHasStockVo> data = skusHasStock.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            if (data != null) {
                //将对应的类型转换为map类型
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                orderConfirmVo.setHasStocks(map);
            }
        }, executor);

        //3.获取用户的积分
        Integer integration = memberRespVo.getIntegration();
        orderConfirmVo.setIntegration(integration);
        //4.其他数据自动计算

        //5.防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        //将令牌存放在redis服务器一份（key值为order:token:userId）
        redisTemplate.opsForValue().set(OrderTokenConstant.ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);
        CompletableFuture.allOf(getAddressFuture, cartFuture).get();
        return orderConfirmVo;
    }

    /**
     * 下单
     *
     * @return
     */
    //全局事务注解
    //@GlobalTransactional 高并发场景不适用Seata
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        //将传来的订单提交数据放到threadLocal方便其他方法取值
        submitVoThreadLocal.set(vo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        //1.验证令牌
        String orderToken = vo.getOrderToken();
        //redis令牌机制，在对比和删除操作要保证是原子操作
        //返回结果0,1  0-令牌验证失败  1-令牌验证成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderTokenConstant.ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if (result == 0L) {
            //令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        } else {
            //令牌验证成功
            //下单：创建订单，验证价格，锁库存...
            //1.创建订单，订单项等信息
            OrderCreateTo order = createOrder();
            BigDecimal payPrice = order.getPayPrice();
            BigDecimal price = vo.getPayPrice();
            if (Math.abs(payPrice.subtract(price).doubleValue()) < 0.01) {
                //金额对比成功
                //3.保存订单
                saveOrder(order);
                //4.库存锁定，只要有异常回滚订单数据
                //订单号，所有订单项(skuId,skuName,num)
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                R r = wmsFeignService.orderLockStock(lockVo);
                if(r.getCode()==0){
                    //锁成功
                    responseVo.setOrder(order.getOrder());
                    //TODO: 默认其他服务失败情况
//                    int i = 10 / 0;
                    //TODO: 订单创建成功，发送消息给MQ
                        rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return responseVo;
                }else{
                    //锁失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
//                    responseVo.setCode(3);
//                    return responseVo;
                }
            } else {
                responseVo.setCode(2);
                return responseVo;
            }
        }
//        //以下验证存在问题，若两个请求都过来，其中一个处理缓慢还未到删除令牌另一个进来还是会导致重复操作
//        String redisToken = redisTemplate.opsForValue().get(OrderTokenConstant.ORDER_TOKEN_PREFIX + memberRespVo.getId());
//        if (orderToken != null && orderToken.equals(redisToken)) {
//            //验证令牌成功,删除令牌
//            redisTemplate.delete(OrderTokenConstant.ORDER_TOKEN_PREFIX + memberRespVo.getId());
//        } else {
//            //验证令牌失败
//        }
    }

    /**
     * 根据订单号查询订单，从而查看订单状态
     * @param orderSn
     * @return
     */
    @Override
    public OrderEntity orderByOrderSn(String orderSn) {
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    /**
     * 关单
     * @param orderEntity
     */
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        OrderEntity entity = this.getById(orderEntity.getId());
        if (entity.getStatus()== OrderStatusEnum.CREATE_NEW.getCode()) {
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            //关单成功，发送消息给mq
            try{
                //TODO 保证消息一定会发送出去，每一个消息都可以做好日志记录（给数据库保存每一个消息的详细信息）
                //TODO 定期扫描数据库将失败的消息再发送一遍；
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other.",orderTo);
            }catch (Exception e){
                //TODO 将没发送成功的消息进行重试发送
            }

        }

    }

    @Override
    public PayVo getPayByOrderSn(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity=this.getOrderByOrderSn(orderSn);
        //设置支付金额取小数点后两位，并且向上取值
        BigDecimal amount = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(amount.toString());
        payVo.setOut_trade_no(orderSn);
        List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity = list.get(0);
        payVo.setSubject(entity.getSkuName());
        payVo.setBody(entity.getSkuAttrsVals());
        return payVo;
    }

    /**
     * 查询出所有订单包括订单项
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id"));
        List<OrderEntity> orderEntities = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(list);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orderEntities);
        return new PageUtils(page);
    }

    /**
     * 支付成功后返回的结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        PaymentInfoEntity entity = new PaymentInfoEntity();
        entity.setOrderSn(vo.getOut_trade_no());
        entity.setAlipayTradeNo(vo.getTrade_no());
        entity.setPaymentStatus(vo.getTrade_status());
        entity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(entity);
        if (vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")){
            String tradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(tradeNo, OrderStatusEnum.PAYED.getCode());
        }
        return null;
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal("" + seckillOrderTo.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);
        //TODO 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        orderItemEntity.setSkuQuantity(seckillOrderTo.getNum());
        orderItemService.save(orderItemEntity);

    }


    private OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity entity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return entity;
    }

    /**
     * 将订单数据进行保存
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        //将订单插入到数据库中
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 创建订单
     *
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1.创建订单号
        String orderSn = IdWorker.getTimeId();
        //2.创建订单实体
        OrderEntity orderEntity = buildOrder(orderSn);
        //3.获取所有的购物项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        //4.验价
        OrderEntity order = computePrice(orderEntity, orderItemEntities);
        orderCreateTo.setOrder(order);
        orderCreateTo.setOrderItems(orderItemEntities);
        orderCreateTo.setPayPrice(order.getPayAmount());
        orderCreateTo.setFare(order.getFreightAmount());
        return orderCreateTo;
    }

    /**
     * 计算订单的各种价格
     *
     * @param orderEntity
     * @param orderItemEntities
     */
    private OrderEntity computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        //订单总额,叠加每一个订单项的总额
        for (OrderItemEntity entity : orderItemEntities) {
            BigDecimal amount = entity.getRealAmount();
            total = total.add(amount);
        }
        orderEntity.setTotalAmount(total);
        //应付总额订单总额+运费(订单总额里的每一个订单项其实都已经做过减去优惠处理，只是我这里没做而已)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //其他优惠总额均先不做处理
        return orderEntity;
    }

    /**
     * 创建订单数据
     *
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        //设置订单号
        orderEntity.setOrderSn(orderSn);
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        //设置会员id
        orderEntity.setMemberId(memberRespVo.getId());
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();
        R fare = memberFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = fare.getData(new TypeReference<FareVo>() {
        });
        BigDecimal farePrice = fareVo.getFare();
        //设置订单实体的运费
        orderEntity.setFreightAmount(farePrice);
        MemberAddressVo address = fareVo.getAddress();
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());
        orderEntity.setReceiverPhone(address.getPhone());
        //设置订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        return orderEntity;
    }

    /**
     * 构建订单项数据
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //这里购物车获取的商品价格均为最新价格
        List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();
        if (currentCartItems != null && currentCartItems.size() > 0) {
            List<OrderItemEntity> collect = currentCartItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 构建某一个订单项数据
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1.订单信息：订单号 orderItemEntity.setOrderSn(orderSn);
        //2.商品的SPU信息
        R r = productFeignService.getSpuIdBySkuId(cartItem.getSkuId());
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setCategoryId(data.getCatalogId());
        //3.商品的SKU信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        itemEntity.setSkuQuantity(cartItem.getCount());
        String skuAttrs = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttrs);
        //4.优惠信息【不做】
        //订单项的价格信息，设置该商品经过优惠后的分解金额realAmount
        //这里的各种优惠金额均未做处理，若存在再设置即可
        BigDecimal price = cartItem.getTotalPrice();
        itemEntity.setRealAmount(price);
        //5.积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().intValue());
        return itemEntity;
    }
}